package com.zyw.weibo.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.emagsoftware.content.pm.PackageMgr;
import cn.emagsoftware.ui.adapterview.AsyncDataExecutor;
import cn.emagsoftware.ui.adapterview.AsyncDataScheduler;
import cn.emagsoftware.ui.adapterview.BaseStepLoadingAdapter;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.util.LogManager;

import com.zyw.weibo.data.User;
import com.zyw.weibo.data.UserListResult;
import com.zyw.weibo.data.remote.NetEngine;
import com.zyw.weibo.data.remote.NetOperatingManager;

public class UserListToWriteMsg extends Base {
	
	private AsyncDataScheduler userScheduler = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if(!Welcome.IS_APP_RUNNING){
			Intent intent = PackageMgr.getLaunchIntentForPackage(this, getPackageName());
			startActivity(intent);
			finish();
			return;
		}
		setContentView(R.layout.userlisttowritemsg);
		
		Button topLeftBtn = (Button)findViewById(R.id.btnTopbarLeft);
		Button homeTitle = (Button)findViewById(R.id.btnTopbarCenter);
		Button topRightBtn = (Button)findViewById(R.id.btnTopbarRight);
		topLeftBtn.setBackgroundResource(R.drawable.generic_btn_back_selector);
		homeTitle.setText(R.string.userlisttowritemsg_title);
		topRightBtn.setBackgroundResource(R.drawable.generic_btn_reload_selector);
		topLeftBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		topRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BaseStepLoadingAdapter adapter = (BaseStepLoadingAdapter)userScheduler.getViewAdapter();
				if(!adapter.isLoading()){
					adapter.clearDataHolders();
					adapter.load(null);
				}
			}
		});
		
		initUserList();
	}
	
	private void initUserList(){
		RelativeLayout listLoadingView = (RelativeLayout)getLayoutInflater().inflate(R.layout.generic_loading, null);
		final ProgressBar listProgressBar = (ProgressBar)listLoadingView.findViewById(R.id.pbLoadingProgress);
		final TextView listProgressDes = (TextView)listLoadingView.findViewById(R.id.tvLoadingDes);
		final Button listRetry = (Button)listLoadingView.findViewById(R.id.btnLoadingRetry);
		final ListView userList = (ListView)findViewById(R.id.lvUserListList);
		int footSpace = (int)getResources().getDimension(R.dimen.main_index_listfoot_space_vertical);
		listLoadingView.setPadding(0, footSpace, 0, footSpace);
		userList.addFooterView(listLoadingView, null, true);
		final BaseStepLoadingAdapter userListAdapter = new BaseStepLoadingAdapter(this) {
			@Override
			public void onBeginLoad(Context arg0, Object arg1) {
				// TODO Auto-generated method stub
				listProgressBar.setVisibility(View.VISIBLE);
				listProgressDes.setVisibility(View.VISIBLE);
				listProgressDes.setText(R.string.generic_loading_loading);
				listRetry.setVisibility(View.GONE);
			}
			@Override
			public List<DataHolder> onLoad(Context arg0, Object arg1, int arg2, int arg3) throws Exception {
				// TODO Auto-generated method stub
				UserListResult result = NetOperatingManager.loadFans(arg0, arg3, LIST_LAZYLOADING_LIMIT, NetOperatingManager.getCurUser().userid);
				setPages(Integer.valueOf(result.pages));
				List<DataHolder> holders = new ArrayList<DataHolder>();
				for(User user:result.list){
					holders.add(new DataHolder(user,TextUtils.isEmpty(user.selfpicture)?0:1) {
						@Override
						public View onCreateView(Context arg0, int arg1, Object arg2) {
							// TODO Auto-generated method stub
							RelativeLayout wrap = (RelativeLayout)LayoutInflater.from(arg0).inflate(R.layout.userlisttowritemsg_list_item, null);
							ImageView head = (ImageView)wrap.findViewById(R.id.ivUserListHead);
							TextView name = (TextView)wrap.findViewById(R.id.tvUserListName);
							name.getPaint().setFakeBoldText(true);
							ViewHolder viewHolder = new ViewHolder(head,name);
							wrap.setTag(viewHolder);
							onUpdateView(arg0,arg1,wrap,arg2,false);
							return wrap;
						}
						@Override
						public void onUpdateView(Context arg0, int arg1, View arg2, Object arg3, boolean arg4) {
							// TODO Auto-generated method stub
							User user = (User)arg3;
							View[] views = ((ViewHolder)arg2.getTag()).getParams();
							ImageView head = (ImageView)views[0];
							TextView name = (TextView)views[1];
							if(TextUtils.isEmpty(user.selfpicture)) {
								head.setImageResource(R.drawable.main_index_list_item_defualthead);
							}else{
								Object asyncData = getAsyncData(0);
								if(asyncData == null) head.setImageResource(R.drawable.main_index_list_item_defualthead);
								else head.setImageDrawable((Drawable)asyncData);
							}
							name.setText(user.nickname);
						}
					});
				}
				return holders;
			}
			@Override
			public void onAfterLoad(Context arg0, Object arg1, Exception arg2) {
				// TODO Auto-generated method stub
				if(arg2 == null){
					listProgressBar.setVisibility(View.GONE);
					listProgressDes.setVisibility(View.VISIBLE);
					if(isLoadedAll()) listProgressDes.setText(R.string.generic_loading_loadcomplete);
					else listProgressDes.setText(R.string.generic_loading_load);
					listRetry.setVisibility(View.GONE);	
				}else{
					LogManager.logE(UserListToWriteMsg.class, "load failed.", arg2);
					listProgressBar.setVisibility(View.GONE);
					listProgressDes.setVisibility(View.GONE);
					listRetry.setVisibility(View.VISIBLE);
				}
			}
		};
		
		listRetry.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				userListAdapter.load(null);
			}
		});
		userList.setAdapter(userListAdapter);
		userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg2 >= userListAdapter.getCount()){
					if(!userListAdapter.isLoadedAll()) userListAdapter.load(null);
				}else{
					User user = (User)userListAdapter.queryDataHolder(arg2).getData();
					Intent returnIntent = new Intent();
					returnIntent.putExtra("nickname", user.nickname);
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			}
		});
		userScheduler = new AsyncDataScheduler(userList, LIST_ASYNCEXECUTING_THREADCOUNT, new AsyncDataExecutor(1,1) {
			@Override
			public void onExecute(List<Integer> arg0, List<DataHolder> arg1, List<Integer> arg2) throws Exception {
				// TODO Auto-generated method stub
				DataHolder holder = arg1.get(0);
				User user = (User)holder.getData();
				String url = NetOperatingManager.URL_HOST + user.selfpicture;
				byte[] data = NetEngine.requestImage(UserListToWriteMsg.this, url);
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				if(bitmap != null) holder.setAsyncData(0, new BitmapDrawable(bitmap));
			}
		});
		
		userListAdapter.load(null);
		userScheduler.start();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		userScheduler.stop();
		userScheduler = null;
	}
	
}
